//计时器
(function($) {
    var min = 0;
    var sec = 0;
    var ms = 0;
    var timer = null;
	
	//开启计时器
	clearInterval(timer);
    timer = setInterval(show, 10);

    //$('#showtime').text();

    //生成时间
    function show() {
        ms++;
		if(sec==60){
			min++;sec=0;
		}
		if(ms==100){
			sec++;ms=0;
		}
		var msStr=ms;
		if(ms<10){
			msStr="0"+ms;
		}
		var secStr=sec;
		if(sec<10){
			secStr="0"+sec;
		}
		var minStr=min;
		if(min<10){
			minStr="0"+min;
		}
        $('#showtime .minute').html(minStr);
        $('#showtime .second').html(secStr);
        $('#showtime .tenms').html(msStr);
    }

	//知识学习
    $.fn.learn = function(settings) {
        var config = $.extend(settings);
        if (config.questions === null) {
            $(this).html('<div class="intro-container slide-container"><h2 class="qTitle">Failed to parse questions.</h2></div>');
            return;
        }
        var superContainer = $(this),
        answers = [],
		questionNum = '',
		questionInfo = '',
		questionBtn = '',
		questionAnswers = '',
        questionsIteratorIndex,
        answersIteratorIndex;
        superContainer.addClass('main-quiz-holder');
		questionsIteratorIndex=0;

		if(sessionStorage.schedule!=null && sessionStorage.schedule>0 && sessionStorage.schedule<=config.questions.length){
			questionsIteratorIndex=sessionStorage.schedule-1;
			init((sessionStorage.schedule-1));
		}else{
			init(0);
		}
		
		function init(index){
			questionAnswers = '',
			questionNum = '习题'+(index+1);//当前习题数
			questionInfo = config.questions[index].question;//习题内容
			questionType = config.questions[index].type;//习题类型
			questionCurrent = '<strong>'+(index+1)+'</strong><span>/'+config.questions.length+'</span>';//当前习题数
			if (index == 0) {
                questionBtn = '<div class="col-50"><p></p></div>';
            }
			if (index !== 0) {
                questionBtn = '<div class="col-50"><button class="btn-prev color-white bouncein">上一题</button></div>';
            }
			if(index<config.questions.length-1){
				questionBtn += '<div class="col-50"><button class="btn-next color-white pull-right bouncein">下一题</button></div>';
			}
			//最后一题
			if(index==config.questions.length-1){
				update_learn_data();//更新学习数据
			}
			for (answersIteratorIndex = 0; answersIteratorIndex < config.questions[index].answers.length; answersIteratorIndex++) {//习题答案
				questionAnswers += '<li data-id="'+config.questions[index].id+'" class="blend-formgroup item fadein-bottom"><div class="blend-formgroup-input">' + String.fromCharCode(64 + parseInt(answersIteratorIndex+1))+'&nbsp;'+config.questions[index].answers[answersIteratorIndex] + '</div></li>';
			}
			superContainer.find('.question-type').html(questionType);
			superContainer.find('.question-number').html(questionNum);
			superContainer.find('.question-info').html(questionInfo);
			superContainer.find('.question-current').html(questionCurrent);
			superContainer.find('.question-btn').html(questionBtn);
			superContainer.find('.answers').html(questionAnswers);

			$(document).find('.btn-next').unbind("click");
			$(document).find('.btn-next').on('click', function() {
				if(index<config.questions.length-1){
					index = ++questionsIteratorIndex;
					$(".answers").html("");
					$(".question-btn").html("");
					superContainer.find('.bird2').removeClass('right wrong ring flash');
					init(index);

					if((index+1)>=config.questions.length){
						sessionStorage.currentIndex = 1;
					}else{
						sessionStorage.currentIndex=index+1;//当前习题
					}
    				sessionStorage.addtimer=$(".minute").text() + ':' + $(".second").text();//答题用时
    				schedule_sync();//同步学习进度

    				//重置计时器
					min=0;
					sec=0;
					ms=0;
			        $('#showtime .minute').html('00');
        			$('#showtime .second').html('00');
        			//$('#showtime .tenms').html('00');
					clearInterval(timer);
    				timer = setInterval(show, 10);

    				//重置sessionStorage
    				sessionStorage.currentIndex=null;//当前习题
    				sessionStorage.addtimer=null;//答题用时
    				sessionStorage.itemId=null;//习题id
    				sessionStorage.isCorrect=null;//是否答对
    				sessionStorage.answer=null;//选中了哪个答案
				}
				return false;
			});

			$(document).find('.btn-prev').unbind("click");
			$(document).find('.btn-prev').on('click', function() {
				if(index>0){
					index = --questionsIteratorIndex;
					$(".answers").html("");
					$(".question-btn").html("");
					superContainer.find('.bird2').removeClass('right wrong ring flash');
					init(index);

    				sessionStorage.currentIndex=index+1;//当前习题
    				sessionStorage.addtimer=$(".minute").text() + ':' + $(".second").text();//答题用时
    				schedule_sync();//同步学习进度

    				//重置计时器
					min=0;
					sec=0;
					ms=0;
			        $('#showtime .minute').html('00');
        			$('#showtime .second').html('00');
        			//$('#showtime .tenms').html('00');
					clearInterval(timer);
    				timer = setInterval(show, 10);

    				//重置sessionStorage
    				sessionStorage.currentIndex=null;//当前习题
    				sessionStorage.addtimer=null;//答题用时
    				sessionStorage.itemId=null;//习题id
    				sessionStorage.isCorrect=null;//是否答对
    				sessionStorage.answer=null;//选中了哪个答案
				}
				return false;
			});

			var canClick=true;
			superContainer.find('.blend-formgroup-input').click(function() {
				if(!canClick)return;
				canClick=false;

				var thisLi = $(this);	
				if(!thisLi.hasClass('right')){
					var userselected=($(this).parents('.blend-formgroup').index()+1);//用户当前选中的答案
					var current=questionsIteratorIndex;//当前问题为所有问题中第几个
					if(userselected==config.questions[current].correctAnswer){//用户当前选中的答案与正确答案是否匹配
						thisLi.parents('.answers').children('.blend-formgroup').find('.blend-formgroup-input').removeClass('right wrong');
						thisLi.addClass('right');
						thisLi.parents('.questions').find('.bird2').addClass('right ring');
						//setTimeout(function(){thisLi.parents('.questions').find('.bird2').removeClass('right');},2000);
						sessionStorage.isCorrect=1;//是否答对，答对了					
					}else{
						thisLi.parents('.answers').children('.blend-formgroup').find('.blend-formgroup-input').removeClass('right wrong');
						thisLi.addClass('wrong');
						thisLi.parents('.questions').find('.bird2').addClass('wrong flash');
						thisLi.parents('.answers').children('.blend-formgroup').eq(config.questions[current].correctAnswer-1).find('.blend-formgroup-input').addClass('right');//显示正确答案
						//setTimeout(function(){thisLi.removeClass('wrong');thisLi.parents('.questions').find('.bird2').removeClass('wrong');},2000);//1秒后错误提示信息消失
						sessionStorage.isCorrect=0;//是否答对，答错了
					}
					++current;
					if(current<config.questions.length){
						//setTimeout(function(){init(current);},2000);//1秒后跳到下一题
					}else{
						$.popup('.popup-finsh');
						// setTimeout(function(){
						// 	window.location.href= sessionStorage.jump_url;
						// },2000);
					}
					sessionStorage.itemId=config.questions[current-1].id;//习题id
					sessionStorage.answer=userselected;//选中了哪个答案
				}
				//2S后才能点击
				// setTimeout(function(){
				// 	canClick=true;
				// },2000);			
			});			
		}	
    };

	//考试
    $.fn.answer = function(settings) {
        var config = $.extend(settings);
        if (config.questions === null) {
            $(this).html('<div class="intro-container slide-container"><h2 class="qTitle">Failed to parse questions.</h2></div>');
            return;
        }
        var superContainer = $(this),
        answers = [],
		questionNum = '',
		questionInfo = '',
		questionBtn = '',
		questionAnswers = '',
        questionsIteratorIndex,
        answersIteratorIndex;
        superContainer.addClass('main-quiz-holder');
		questionsIteratorIndex=0;
		init(0);

		var correctCount=0;//答对题数
		var array_record=new Array();
		
		function init(index){
			questionAnswers = '',
			questionNum = '习题'+(index+1);//当前习题数
			//alert(questionNum);	
			questionInfo = config.questions[index].question;//习题内容
			questionType = config.questions[index].type;//习题类型
			questionCurrent = '<strong>'+(index+1)+'</strong><span>/'+config.questions.length+'</span>';//当前习题数
			if(index<=config.questions.length-1){
				questionBtn = '<button class="btn-next color-white pull-right bouncein">下一题</button>';
			}else{
				questionBtn = '';				
			}
			for (answersIteratorIndex = 0; answersIteratorIndex < config.questions[index].answers.length; answersIteratorIndex++) {//习题答案
				questionAnswers += '<li data-id="'+config.questions[index].id+'" class="blend-formgroup item fadein-bottom"><div class="blend-formgroup-input">' + String.fromCharCode(64 + parseInt(answersIteratorIndex+1))+'&nbsp;'+config.questions[index].answers[answersIteratorIndex] + '</div></li>';
			}
			superContainer.find('.question-type').html(questionType);
			superContainer.find('.question-number').html(questionNum);
			superContainer.find('.question-info').html(questionInfo);
			superContainer.find('.question-current').html(questionCurrent);
			//superContainer.find('.question-btn').html(questionBtn);
			superContainer.find('.answers').html(questionAnswers);

			sessionStorage.itemId=config.questions[index].id;//习题id
			sessionStorage.question=config.questions[index].question;//习题内容
			//superContainer.find('.next').unbind("click");
			$(document).on('click', '.btn-next', function() {
				if((index<config.questions.length-1) && (superContainer.find('.blend-formgroup-input').hasClass('right') || superContainer.find('.blend-formgroup-input').hasClass('wrong')) ){
					index = ++questionsIteratorIndex;
					$(".answers").html("");
					$(".question-btn").html("");
					superContainer.find('.bird2').removeClass('right wrong ring flash');
					init(index);
				}
				return false;
			});

			//superContainer.find('.prev').unbind("click");
			$(document).on('click', '.btn-prev', function() {
				if(index>0){
					index = --questionsIteratorIndex;
					$(".answers").html("");
					$(".question-btn").html("");
					superContainer.find('.bird2').removeClass('right wrong ring flash');
					init(index);
				}
				return false;
			});
			
			var canClick=true;
			superContainer.find('.blend-formgroup-input').click(function() {
				if(!canClick)return;
				canClick=false;

				var thisLi = $(this);
				if(!thisLi.hasClass('right')){     				
					var userselected=($(this).parents('.blend-formgroup').index()+1);//用户当前选中的答案
					var current=questionsIteratorIndex;//当前问题为所有问题中第几个

					if(userselected==config.questions[current].correctAnswer){//用户当前选中的答案与正确答案是否匹配
						thisLi.parents('.answers').children('.blend-formgroup').find('.blend-formgroup-input').removeClass('right wrong');
						thisLi.addClass('right');
						thisLi.parents('.questions').find('.bird2').addClass('right ring');
						//setTimeout(function(){thisLi.parents('.questions').find('.bird2').removeClass('right');},2000);
						correctCount=correctCount+1;
						sessionStorage.isCorrect=1;//是否答对，答对了
					}else{
						thisLi.parents('.answers').children('.blend-formgroup').find('.blend-formgroup-input').removeClass('right wrong');
						thisLi.addClass('wrong');
						thisLi.parents('.questions').find('.bird2').addClass('wrong flash');
						thisLi.parents('.answers').children('.blend-formgroup').eq(config.questions[current].correctAnswer-1).find('.blend-formgroup-input').addClass('right');//显示正确答案
						//setTimeout(function(){thisLi.removeClass('wrong');thisLi.parents('.questions').find('.bird2').removeClass('wrong');},2000);//2秒后错误提示信息消失
						sessionStorage.isCorrect=0;//是否答对，答错了
					}

					//考试记录	
					sessionStorage.answer=config.questions[current].answers[userselected-1];//选中了哪个答案
					var arr  ={
         				itemId : sessionStorage.itemId,
         				question : sessionStorage.question,
         				answer : sessionStorage.answer,
         				isCorrect : sessionStorage.isCorrect
     				}
     				array_record.push(arr);
     				console.log(JSON.stringify(array_record));

					++current;
					if(current<config.questions.length){
						//显示下一题按钮
						superContainer.find('.question-btn').html(questionBtn);
						//setTimeout(function(){init(current);},2000);//1秒后跳到下一题
					}else{
						//考试结束，存储相关数据
						sessionStorage.correctCount=correctCount;//答对题数
						// sessionStorage.score=(correctCount/config.questions.length)*100;//考试分数
						sessionStorage.score=correctCount*5;
						sessionStorage.timer=$('#showtime').text();//考试用时
						var minute = $(".minute").text();
  						var second = $(".second").text();
  						var tenms = $(".tenms").text();
  						sessionStorage.times = minute + ':' + second + ':' + tenms;
  						console.log(sessionStorage.times);

  						sessionStorage.json_record=JSON.stringify(array_record);
  						
						setTimeout(function(){
							chk_time();
							// window.location.href= sessionStorage.jump_url;
						},1000);
					}
				}
				//2S后才能点击
				// setTimeout(function(){
				// 	canClick=true;
				// },2000);			
			});			
		}	
    };
})(Zepto);